cmake_minimum_required(VERSION 3.10)

# 项目名称和版本设置
project(MyQtApp VERSION 1.0.0 LANGUAGES CXX)

# 设置C++标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_compile_options(-finput-charset=UTF-8)
add_compile_options(-fexec-charset=UTF-8)


# 自动处理UI、资源和MOC文件
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOMOC ON)

# 查找所需的Qt组件
find_package(Qt5 REQUIRED COMPONENTS
    Core
    Gui
    Widgets
    # 添加其他需要的Qt模块
)

# 根据不同平台设置特定选项
if(WIN32)
    # Windows平台特定设置
    add_definitions(-D_WINDOWS)
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:WINDOWS")
    
    # 如果使用MSVC编译器
    if(MSVC)
        add_compile_options(/MP)  # 启用多处理器编译
    endif()
    
elseif(UNIX AND NOT APPLE)
    # Linux平台(包括树莓派)特定设置
    add_definitions(-D_LINUX)
    
    # 树莓派特定设置
    if(ARM)
        # 可以添加针对ARM的优化选项
        add_compile_options(-march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard)
    endif()
    
    # 设置安装路径
    set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()

# 设置可执行文件输出目录
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)

# 收集源文件
file(GLOB_RECURSE SOURCES "src/*.cpp")
file(GLOB_RECURSE HEADERS "src/*.h")
file(GLOB_RECURSE FORMS "src/*.ui")
file(GLOB_RECURSE RESOURCES "src/*.qrc")

# 创建可执行文件
add_executable(${PROJECT_NAME}
    ${SOURCES}
    ${HEADERS}
    ${FORMS}
    ${RESOURCES}
)

# 链接Qt库
target_link_libraries(${PROJECT_NAME}
    Qt5::Core
    Qt5::Gui
    Qt5::Widgets
    # 链接其他需要的Qt模块
)

# Windows平台下拷贝Qt DLL文件
if(WIN32)
    # 获取Qt库路径
    get_target_property(QT_LOCATION Qt5::Widgets LOCATION)
    get_filename_component(QT_DLL_DIR ${QT_LOCATION} DIRECTORY)
    
    # 添加自定义目标，在构建后拷贝DLL
    add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${QT_DLL_DIR}/Qt5Core.dll"
            "${QT_DLL_DIR}/Qt5Gui.dll"
            "${QT_DLL_DIR}/Qt5Widgets.dll"
            $<TARGET_FILE_DIR:${PROJECT_NAME}>
    )
    
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE")
    
    target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/lib/windows")
    # 链接 ControlCAN.lib
    target_link_libraries(${PROJECT_NAME} "${CMAKE_SOURCE_DIR}/lib/windows/ControlCAN.lib")
endif() 

# 安装规则(适用于Linux/树莓派)
if(UNIX AND NOT APPLE)
    install(TARGETS ${PROJECT_NAME}
        RUNTIME DESTINATION bin
    )
    target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/lib/linux")
    # 链接 libcontrolcan.so
    target_link_libraries(${PROJECT_NAME} "${CMAKE_SOURCE_DIR}/lib/arm/64bit/libcontrolcan.so")
    
    # 安装桌面文件(可选)
    # install(FILES ${PROJECT_NAME}.desktop DESTINATION share/applications)
    
    # 安装图标(可选)
    # install(FILES icons/${PROJECT_NAME}.png DESTINATION share/pixmaps)
endif()

# 添加可选的测试目标(如果需要)
# enable_testing()
# add_subdirectory(tests)